"""
cron: */5 9-15 * * 1-5
new Env('基金数据采集');
"""
import requests
import os
import mysql.connector
from datetime import datetime

# 获取环境变量
host = os.environ.get('HOST')
user = os.environ.get('USER')
password = os.environ.get('PASSWORD')
database = os.environ.get('DATABASE')

print("正在获取环境变量...")
print(f"数据库地址：{host}")
print(f"数据库用户名：{user}")
print(f"数据库密码：{password}")
print(f"数据库名称：{database}")

# 发送HTTP请求获取基金数据
print("发送HTTP请求获取基金数据...")
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Referer': 'http://fund.eastmoney.com/'
}

# 获取热门基金列表
url = 'http://api.fund.eastmoney.com/FundGuZhi/GetFundGZList'
params = {
    'type': 1,
    'sort': 'RZDF',
    'orderType': 'desc',
    'canbuy': 1,
    'pageIndex': 1,
    'pageSize': 20
}

response = requests.get(url, headers=headers, params=params)

# 连接数据库
connection = mysql.connector.connect(
    host=host,
    user=user,
    password=password,
    database=database
)

cursor = connection.cursor()

# 创建表（如果不存在）
create_table_query = """
CREATE TABLE IF NOT EXISTS ningm_fund (
    id INT AUTO_INCREMENT PRIMARY KEY,
    fund_code VARCHAR(10) NOT NULL,
    fund_name VARCHAR(100) NOT NULL,
    net_value DECIMAL(10,4),
    increase_rate DECIMAL(10,2),
    update_time DATETIME,
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_fund_code (fund_code),
    INDEX idx_create_time (create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
"""
cursor.execute(create_table_query)

# 删除旧数据（保留7天内的数据）
print("删除旧数据...")
delete_query = "DELETE FROM ningm_fund WHERE create_time < DATE_SUB(NOW(), INTERVAL 7 DAY)"
cursor.execute(delete_query)

# 解析并保存数据
print("解析并保存基金数据...")
if response.status_code == 200:
    data = response.json()
    fund_list = data.get('Data', {}).get('list', [])
    
    for fund in fund_list:
        fund_code = fund.get('FCODE', '')
        fund_name = fund.get('SHORTNAME', '')
        net_value = fund.get('NAV', 0)
        increase_rate = fund.get('RZDF', 0)
        
        print(f"正在保存基金数据: {fund_code} {fund_name}")
        insert_query = """
            INSERT INTO ningm_fund 
            (fund_code, fund_name, net_value, increase_rate, update_time) 
            VALUES (%s, %s, %s, %s, %s)
        """
        insert_values = (
            fund_code,
            fund_name,
            net_value,
            increase_rate,
            datetime.now()
        )
        cursor.execute(insert_query, insert_values)

connection.commit()
cursor.close()
connection.close()

print("数据保存完成！") 